import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:yuellyfactory/util/ToastUtil.dart';

import '../../eventbus/EventBusUtil.dart';
import '../../eventbus/EventRefreshBase.dart';
import '../../util/BaseRequest.dart';
import '../../util/ColorUtil.dart';
import '../../util/ViewUtil.dart';
import '../dto/PriceParm.dart';
import '../dto/PricePart.dart';
import '../dto/PriceSerial.dart';


class EditBrandVC extends StatefulWidget {
  final VoidCallback callback;
  final PricePart pricePart;
  const EditBrandVC({super.key, required this.callback, required this.pricePart});

  @override
  State<EditBrandVC> createState() => _EditBrandVCState();
}

class _EditBrandVCState extends State<EditBrandVC> {
  PricePart partData=PricePart();
  PricePart parmPart=PricePart();
  Map dataValues={};
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    partData=widget.pricePart;
    //至少 要有parentId;获取typeId然后拿到parmList
    if(partData.parmData.isNotEmpty){
      List list=jsonDecode(partData.parmData);
      for(var item in list){
        dataValues[item["name"]]=item["value"];
      }
    }

    if(partData.remarkData.isNotEmpty){
      List list=jsonDecode(partData.remarkData);
      for(var item in list){
        dataValues[item["name"]]=item["value"];
      }
    }
    getParms();

  }

  void getParms(){
    BaseRequest.postHttp('price/typeparmbyid',parameters: {"id":widget.pricePart.parentId}, canTip: true, context: context, onSuccess: (data){
      dynamic datas=data["data"];
      var part=PricePart.fromJson(datas);
      parmPart=part;
      setState(() {

      });
    }, onError: (error){});
  }

  @override
  Widget build(BuildContext context) {
    return ShadSheet(
      onClosing: (){
        widget.callback();
      },
      constraints: const BoxConstraints(minWidth: 800,maxWidth: 800),

      title: Row(
        children: [
          const Text('品牌编辑'),
          const SizedBox(width: 50,),
          ViewUtil.doneIcon("保存", (){
            save();
          })
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(width: 350,
              child:
              Row(children: [
                SizedBox(width: 130,child: const Text("名称:",style: TextStyle(color: Colors.black)),),
                Expanded(child: ShadInput(
                  textAlign: TextAlign.start,
                  initialValue: partData.name,
                  placeholder: const Text("请输入名称"),
                  onChanged: (value){
                    debugPrint(value);
                    partData.name=value;

                  },
                ))
                ,],)),
          const SizedBox(height: 10),
          const Text('品牌概况',style: TextStyle(color: Colors.black),),
          Wrap(
            crossAxisAlignment: WrapCrossAlignment.center,
            runAlignment: WrapAlignment.start,
            direction: Axis.horizontal, // 水平方向排列（默认）
            alignment: WrapAlignment.start, // 水平靠左（默认值，可省略）
            spacing: 10, // 子组件横向间距
            runSpacing: 0, // 换行后纵向间距
            children: getParmView(),
          ),
          const SizedBox(height: 10),


          const Text('品牌详情',style: TextStyle(color: Colors.black),),
          Wrap(
            crossAxisAlignment: WrapCrossAlignment.center,
            runAlignment: WrapAlignment.start,
            direction: Axis.horizontal, // 水平方向排列（默认）
            alignment: WrapAlignment.start, // 水平靠左（默认值，可省略）
            spacing: 10, // 子组件横向间距
            runSpacing: 0, // 换行后纵向间距
            children: getDataView(),
          ),

          const SizedBox(height: 16),

        ],
      ),
    );
  }

  List<Widget> getParmView(){
    List<Widget> widgets=[];


    for(PriceParm parm in parmPart.brandParmList){

      List selectItems=[];
      if(parm.rule.isNotEmpty){
        List list=jsonDecode(parm!.rule);
        for (var item in list) {
          selectItems.add(item.toString());
        }
      }
      var initValue="";
      if(dataValues.containsKey(parm.id)){
        initValue=dataValues[parm.id];
      }else{
        if(parm.value.isNotEmpty){
          initValue=parm.value;
        }
      }

      parm.value=initValue;

      widgets.add(
          SizedBox(width: 350,
              child:
              Row(children: [

                SizedBox(width: 130,child: Text("${parm.name}:",style: TextStyle(color: parm.required==1&&parm.value.isEmpty?Colors.red:Colors.black),),),
                if(parm.type==0)
                  Expanded(child: ShadInput(
                    decoration: ShadDecoration(
                      border: ShadBorder.all(color: parm.required==1&&parm.value.isEmpty&&parm.value.isEmpty?Colors.red:Colors.black ),
                    ),
                    suffix: Text(parm.unit??""),
                    textAlign: TextAlign.start,
                    initialValue:initValue,
                    placeholder: Text("请输入${parm.name}"),
                    onChanged: (value){
                      debugPrint(value);
                      parm.value=value;
                      dataValues[parm.id]=value;
                      setState(() {

                      });
                    },
                  )),
                if(parm.type==1)
                  Expanded(child:  ShadSelect<String>(
                    decoration: ShadDecoration(
                      border: ShadBorder.all(color: parm.required==1&&parm.value.isEmpty&&parm.value.isEmpty?Colors.red:Colors.black ),
                    ),
                    minWidth: 350,
                    onChanged: (value){
                      if (value != null && parm != null) {  // 增加parm的空判断
                        parm.value = value;  // 移除不必要的toString()
                        dataValues[parm.id]=value;
                        setState(() {

                        });
                      }
                    },
                    initialValue: initValue,
                    options: selectItems.map((item) {
                      final value = item.isNotEmpty ? item : '';
                      return ShadOption<String>(
                        value: value,
                        child: Text(value),
                      );
                    }).toList(),
                    selectedOptionBuilder: (context, value) {
                      // 处理value可能为null的情况
                      if (value == null || value.isEmpty || value == 'none') {
                        return const Text('请选择');
                      }
                      return Text(value);
                    },
                    placeholder: const Text('请选择'),

                  ),),

              ],)));
    }
    return widgets;
  }


  List<Widget> getDataView(){
    List<Widget> widgets=[];

    for(PriceParm parm in parmPart.brandDataList){

      List selectItems=[];
      if(parm.rule.isNotEmpty){
        List list=jsonDecode(parm!.rule);
        for (var item in list) {
          selectItems.add(item.toString());
        }
      }
      var initValue="";
      if(dataValues.containsKey(parm.id)){
        initValue=dataValues[parm.id];
      }else{
        if(parm.value.isNotEmpty){
          initValue=parm.value;
        }
      }
      parm.value=initValue;
      widgets.add(
          SizedBox(width: 350,
              child:
              Row(children: [

                SizedBox(width: 130,child: Text("${parm.name}:",style: TextStyle(color: parm.required==1&&parm.value.isEmpty?Colors.red:Colors.black),),),
                if(parm.type==0)
                  Expanded(child: ShadInput(
                    decoration: ShadDecoration(
                      border: ShadBorder.all(color: parm.required==1&&parm.value.isEmpty&&parm.value.isEmpty?Colors.red:Colors.black ),
                    ),
                    suffix: Text(parm.unit??""),
                    textAlign: TextAlign.start,
                    initialValue:initValue,
                    placeholder: Text("请输入${parm.name}"),
                    onChanged: (value){
                      debugPrint(value);
                      parm.value=value;
                      dataValues[parm.id]=value;
                      setState(() {

                      });
                    },
                  )),
                if(parm.type==1)
                  Expanded(child:  ShadSelect<String>(
                    decoration: ShadDecoration(
                      border: ShadBorder.all(color: parm.required==1&&parm.value.isEmpty&&parm.value.isEmpty?Colors.red:Colors.black ),
                    ),
                    minWidth: 350,
                    onChanged: (value){
                      if (value != null && parm != null) {  // 增加parm的空判断
                        parm.value = value;  // 移除不必要的toString()
                        dataValues[parm.id]=value;
                        setState(() {

                        });
                      }
                    },
                    initialValue: initValue,
                    options: selectItems.map((item) {
                      final value = item.isNotEmpty ? item : '';
                      return ShadOption<String>(
                        value: value,
                        child: Text(value),
                      );
                    }).toList(),
                    selectedOptionBuilder: (context, value) {
                      // 处理value可能为null的情况
                      if (value == null || value.isEmpty || value == 'none') {
                        return const Text('请选择');
                      }
                      return Text(value);
                    },
                    placeholder: const Text('请选择'),

                  ),),

              ],)));
    }
    return widgets;
  }

  void save(){
    var name=partData.name;
    if(name.isEmpty){
      ToastUtil.showToast('请输入名称');
      return;
    }
    bool result=true;
    var parms=[];
    for(PriceParm parm in parmPart.brandParmList){
      var value=parm.value;
      // if(parm.required==1&&value.isEmpty){
      //   result=false;
      //   if(parm.type==0){
      //     ToastUtil.showToast('请输入${parm.name}');
      //   }else{
      //     ToastUtil.showToast('请选择${parm.name}');
      //   }
      //
      //   break;
      // }else{
      //   parms.add({"name":parm.id,"value":value});
      // }
      parms.add({"name":parm.id,"value":value});
    }

    var datas=[];
    for(PriceParm parm in parmPart.brandDataList){
      var value=parm.value;
      // if(parm.required==1&&value.isEmpty){
      //   result=false;
      //   if(parm.type==0){
      //     ToastUtil.showToast('请输入${parm.name}');
      //   }else{
      //     ToastUtil.showToast('请选择${parm.name}');
      //   }
      //
      //   break;
      // }else{
      //
      // }
      datas.add({"name":parm.id,"value":value});
    }

    if(!result){
      return;
    }
    var parm={
      "name":name,
      "parentId":partData.parentId,
      "parm":parms,
      "remark":datas,
      "id":partData.id
    };
    BaseRequest.postHttp("price/editpart",parameters: parm, canTip: true, context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        ToastUtil.showToast("编辑成功");
        eventBus.fire(EventRefreshBase());
        Navigator.pop(context);

      }
    }, onError: (error){

    });
  }
}
